<script lang="ts" setup>
import { ref, computed } from 'vue'

interface PaymentParams {
  timeStamp: string
  nonceStr: string
  package: string
  signType: string
  paySign: string
}

// 配置常量
const MIN_AMOUNT = 5 // 最小金额改为5元
const MAX_AMOUNT = 5000
const FIXED_AMOUNTS = [5, 10, 50, 100, 200, 500, 1000] // 增加5元选项

// 响应式数据
const selectedAmount = ref<number | null>(null)
const customAmount = ref('')
const isLoading = ref(false)
const errorMessage = ref('')

// 计算属性
const amountToPay = computed(() => {
  return selectedAmount.value || Number(customAmount.value) || 0
})

const isMultipleOfFive = computed(() => {
  return amountToPay.value % 5 === 0
})

const isValidAmount = computed(() => {
  return (
    isMultipleOfFive.value && amountToPay.value >= MIN_AMOUNT && amountToPay.value <= MAX_AMOUNT
  )
})

// 选择固定金额
const selectAmount = (amount: number) => {
  selectedAmount.value = amount
  customAmount.value = ''
  errorMessage.value = ''
}

// 处理自定义金额输入
const handleCustomInput = (value: string) => {
  // 过滤非数字字符并限制小数点
  customAmount.value = value.replace(/[^0-9]/g, '')
  selectedAmount.value = null

  const amount = Number(customAmount.value)
  if (amount === 0) {
    errorMessage.value = ''
    return
  }

  if (!isMultipleOfFive.value) {
    errorMessage.value = '金额必须是5的整倍数'
  } else if (amount < MIN_AMOUNT) {
    errorMessage.value = `最低充值金额为${MIN_AMOUNT}元`
  } else if (amount > MAX_AMOUNT) {
    errorMessage.value = `最高充值金额为${MAX_AMOUNT}元`
  } else {
    errorMessage.value = ''
  }
}

// 提交支付
const handlePayment = async () => {
  if (!isValidAmount.value) {
    showErrorToast()
    return
  }

  try {
    isLoading.value = true
    const paymentParams: PaymentParams = await fetchPaymentParams(amountToPay.value)

    const res = await uni.requestPayment({
      ...paymentParams,
      success: () => handlePaymentSuccess(),
      fail: (err) => handlePaymentError(err),
    })
  } catch (error) {
    handlePaymentError(error)
  } finally {
    isLoading.value = false
  }
}

// 显示错误提示
const showErrorToast = () => {
  let message = '请输入有效金额'
  if (!isMultipleOfFive.value) {
    message = '金额必须是5的整倍数'
  } else if (amountToPay.value < MIN_AMOUNT) {
    message = `最低充值${MIN_AMOUNT}元`
  } else if (amountToPay.value > MAX_AMOUNT) {
    message = `最高充值${MAX_AMOUNT}元`
  }

  uni.showToast({
    title: message,
    icon: 'none',
    duration: 2000,
  })
}

// 模拟获取支付参数（保持不变）
const fetchPaymentParams = async (amount: number): Promise<PaymentParams> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        timeStamp: Date.now().toString(),
        nonceStr: Math.random().toString(36).substr(2),
        package: `prepay_id=模拟支付ID${amount}`,
        signType: 'MD5',
        paySign: '模拟签名',
      })
    }, 500)
  })
}

// 支付成功处理（保持不变）
const handlePaymentSuccess = () => {
  uni.showToast({
    title: '支付成功',
    icon: 'success',
    duration: 2000,
  })
  selectedAmount.value = null
  customAmount.value = ''
}

// 支付失败处理（保持不变）
const handlePaymentError = (error: any) => {
  console.error('支付失败:', error)
  uni.showToast({
    title: '支付失败，请重试',
    icon: 'none',
    duration: 2000,
  })
}
</script>

<template>
  <view class="container">
    <!-- 头部 -->
    <view class="header">
      <text class="title">账户充值</text>
      <text class="subtitle">金额需为5的整倍数（元）</text>
    </view>

    <!-- 金额选项 -->
    <view class="amount-grid">
      <button
        v-for="(amount, index) in FIXED_AMOUNTS"
        :key="index"
        :class="['amount-card', { active: selectedAmount === amount }]"
        @tap="selectAmount(amount)"
      >
        <text class="amount">{{ amount }}</text>
        <text class="unit">元</text>
      </button>
    </view>

    <!-- 自定义金额 -->
    <view class="custom-amount">
      <view class="input-group">
        <text class="prefix">¥</text>
        <input
          class="input"
          type="number"
          :value="customAmount"
          placeholder="输入5的整倍金额"
          :disabled="isLoading"
          @input="(e) => handleCustomInput(e.detail.value)"
          placeholder-style="color: #999;"
          step="5"
        />
      </view>
      <view class="hint-group">
        <text class="hint">支持{{ MIN_AMOUNT }}-{{ MAX_AMOUNT }}元</text>
        <text class="error" v-if="errorMessage">{{ errorMessage }}</text>
      </view>
    </view>

    <!-- 支付按钮 -->
    <button
      class="pay-button"
      :class="{ disabled: !isValidAmount || isLoading }"
      :disabled="!isValidAmount || isLoading"
      @tap="handlePayment"
    >
      <text v-if="!isLoading">立即支付 ¥{{ amountToPay }}</text>
      <view v-else class="loading">
        <text>处理中...</text>
        <view class="spinner"></view>
      </view>
    </button>
  </view>
</template>

<style lang="scss" scoped>
$primary-color: #2979ff;
$error-color: #ff4d4f;

// 新增错误提示样式
.error {
  color: $error-color;
  font-size: 24rpx;
  margin-top: 8rpx;
}

.hint-group {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

// 调整金额卡片的激活样式
.amount-card.active {
  border-color: $primary-color;
  background: rgba($primary-color, 0.05);
  .amount {
    color: $primary-color;
  }
}

// 其他样式保持不变...
$primary-color: #2979ff;
$success-color: #52c41a;
$error-color: #ff4d4f;
$text-color: #333;
$border-color: #eee;

.container {
  padding: 24rpx;
  min-height: 100vh;
  background: #f8f8f8;
}

.header {
  padding: 40rpx 0;
  text-align: center;
  .title {
    display: block;
    font-size: 36rpx;
    font-weight: 500;
    color: $text-color;
    margin-bottom: 16rpx;
  }
  .subtitle {
    font-size: 28rpx;
    color: #666;
  }
}

.amount-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 24rpx;
  padding: 24rpx 0;

  .amount-card {
    aspect-ratio: 1;
    width: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    background: white;
    border-radius: 16rpx;
    border: 2rpx solid $border-color;
    transition: all 0.2s ease;
    padding: 0;

    &.active {
      border-color: $primary-color;
      background: rgba($primary-color, 0.05);
      .amount {
        color: $primary-color;
      }
    }

    .amount {
      font-size: 40rpx;
      font-weight: 500;
      color: $text-color;
    }

    .unit {
      font-size: 24rpx;
      color: #666;
      margin-top: 8rpx;
    }
  }
}

.custom-amount {
  margin: 40rpx 0;
  padding: 24rpx;
  background: white;
  border-radius: 16rpx;

  .input-group {
    display: flex;
    align-items: center;
    border-bottom: 2rpx solid $border-color;
    padding-bottom: 16rpx;
    margin-bottom: 16rpx;

    .prefix {
      font-size: 40rpx;
      color: $text-color;
      margin-right: 16rpx;
    }

    .input {
      flex: 1;
      height: 80rpx;
      font-size: 36rpx;
      color: $text-color;
    }
  }

  .hint {
    font-size: 24rpx;
    color: #999;
  }
}

.pay-button {
  width: 100%;
  height: 96rpx;
  line-height: 96rpx;
  font-size: 32rpx;
  color: white;
  background: $primary-color;
  border-radius: 48rpx;
  transition: all 0.2s ease;

  &.disabled {
    background: #ccc;
    opacity: 0.7;
  }

  .loading {
    display: flex;
    align-items: center;
    justify-content: center;

    .spinner {
      width: 32rpx;
      height: 32rpx;
      border: 4rpx solid rgba(255, 255, 255, 0.3);
      border-top-color: white;
      border-radius: 50%;
      margin-left: 16rpx;
      animation: spin 1s linear infinite;
    }
  }
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}
</style>
